package models

import (
	"awesomeProject1/微信登录demo/dao"
)

type LoginModels struct {
	//openid
	Openid string `json:"openid" form:"openid" binding:"required" gorm:"column:openid"`
	//session_key
	SessionKey string `json:"session_key" form:"session_key" binding:"required" gorm:"column:sessionKey"`
}

type GetCode struct {
	JsCode string `json:"js_code" form:"js_code" binding:"required"`
}

func InsertSessionKey(SessionKey, Openid string) (err error) {
	//先查询数据库有没有前端传递过来的sessionKey
	strSql1 := `select openid from wxlogin2 where openid = ?`
	var v []LoginModels
	err = dao.DB.Raw(strSql1, Openid).Scan(&v).Error
	if err != nil {
		return err
	}
	if len(v) == 0 {
		strSQL := `insert into wxlogin2(phone, openid, sessionKey) VALUES (?,?,?);`
		err = dao.DB.Exec(strSQL, nil, Openid, SessionKey).Error
		if err != nil {
			return err
		}
		return nil
	} else {
		strSql := `update wxlogin2 set sessionKey = ?,openid = ? where openid = ?`
		err := dao.DB.Exec(strSql, SessionKey, Openid, Openid).Error
		if err != nil {
			return err
		}
	}
	return nil
}
